<script lang="ts" setup>
import { reactive, ref, toRaw, unref } from 'vue';

import { useFs } from '@fast-crud/fast-crud';
import { Button, Flex } from 'ant-design-vue';

import { DefGenTableApi } from '#/api/devOperation/developer/defGenTable';
import { TemplateEnum } from '#/enums/system';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import { blobToObj, downloadByResponse } from '#/utils/file/download';

import { createCrudOptions } from '../data/generatorCrud';

defineOptions({
  name: '生成代码',
  inheritAttrs: false,
});

const formRef = ref();
const formState = reactive<{ tableIdListRef: string[] }>({
  tableIdListRef: [],
});
const buttonLoading = ref(false);
const fieldTemplate = ref<Record<string, string>>({});
const tableIdListRef = ref<string[]>([]);
const { createMessage } = useMessage();

const { crudBinding } = useFs({ createCrudOptions, context: toRaw(formState) });

const load = async (tableId: string) => {
  const tableIdList = tableId.includes(',') ? tableId.split(',') : [tableId];
  tableIdListRef.value = tableIdList;

  const defFileOverrideStrategy =
    await DefGenTableApi.getDefFileOverrideStrategy();
  formRef.value.setFormData(defFileOverrideStrategy, { mergeForm: false });
};

async function download(template: TemplateEnum) {
  buttonLoading.value = true;
  try {
    const response = await DefGenTableApi.downloadZip(
      unref(tableIdListRef),
      template,
    );
    if (response) {
      downloadByResponse(response);
      createMessage.success($t('common.tips.downloadSuccess'));
    } else {
      createMessage.error(
        '下载失败，请认真检查【生成信息】是否填写完整并保存成功！',
      );
    }
  } catch (error: any) {
    buttonLoading.value = false;
    if (error?.response?.data) {
      const obj = (await blobToObj(error?.response?.data)) as any;
      createMessage.error(obj.msg);
    } else {
      const obj = (await blobToObj(error)) as any;
      createMessage.error(obj.msg);
    }
  } finally {
    buttonLoading.value = false;
  }
}

async function generator(template: TemplateEnum) {
  try {
    buttonLoading.value = true;

    const params = await formRef.value.getFormData();

    const ft = await DefGenTableApi.getFieldTemplate(template);
    fieldTemplate.value = ft;

    const fileOverrideConfig: Record<string, string> = {};
    for (const key in params) {
      fileOverrideConfig[fieldTemplate.value[key] as string] = params[key];
    }

    const defGenVo = {
      ids: unref(tableIdListRef),
      template,
      fileOverrideConfig,
    };
    await DefGenTableApi.generatorCode(defGenVo);

    createMessage.success('代码生成成功，请在[生成路径]查看');
  } finally {
    buttonLoading.value = false;
  }
}

defineExpose({ load });
</script>

<template>
  <FsForm ref="formRef" v-bind="crudBinding.editForm" />

  <Flex gap="small" class="mt-4">
    <Button :loading="buttonLoading" @click="download(TemplateEnum.WEB_PLUS)">
      下载前端(Vben)
    </Button>
    <Button
      :loading="buttonLoading"
      class="ml-2"
      @click="download(TemplateEnum.WEB_SOYBEAN)"
    >
      下载前端(Soybean)
    </Button>
    <Button
      :loading="buttonLoading"
      class="ml-2"
      @click="download(TemplateEnum.WEB_VBEN5)"
    >
      下载前端(Vben5)
    </Button>
    <Button
      :loading="buttonLoading"
      class="ml-2"
      @click="download(TemplateEnum.BACKEND)"
    >
      下载后端
    </Button>
    <Button
      type="primary"
      :loading="buttonLoading"
      class="ml-2"
      @click="generator(TemplateEnum.WEB_PLUS)"
    >
      生成前端(Vben)
    </Button>
    <Button
      type="primary"
      :loading="buttonLoading"
      class="ml-2"
      @click="generator(TemplateEnum.WEB_SOYBEAN)"
    >
      生成前端(Soybean)
    </Button>
    <Button
      type="primary"
      :loading="buttonLoading"
      class="ml-2"
      @click="generator(TemplateEnum.WEB_VBEN5)"
    >
      生成前端(Vben5)
    </Button>
    <Button
      type="primary"
      :loading="buttonLoading"
      class="ml-2"
      @click="generator(TemplateEnum.BACKEND)"
    >
      生成后端
    </Button>
  </Flex>
</template>
